import type { Module } from 'vuex'
import { getPermission, wxLogin } from "../../api/auth";
import { UserInfo, UserStoreState } from "../../types/storeTypes";
import { getUserData } from "../../api/manage";
import { UserPermissionDAT } from "../../types/responseTypes";


const userStore: Module<UserStoreState, any> = {
    state() {
        return {
            hasLogIn: !!uni.getStorageSync('token'),
            userInfo: uni.getStorageSync('userInfo') || {},
            isFilledData: false,
            hasEnroll: false,
            permissions: [],
            isUpdatauserinfo: false,
            isUpdataSchoolinfo: false
        }
    },

    getters: {
        OPENID: state => state.userInfo.OPENID,
        // SESSION_KEY: state => state.userInfo.SESSION_KEY,
        permissions: state => state.permissions
    },

    mutations: {
        SET_USERINFO(state: any, ISget: boolean) {
            state.isUpdatauserinfo = ISget
        },
        SET_SCHOOLINFO(state: any, ISget: boolean) {
            state.isUpdataSchoolinfo = ISget
        },
        SET_LOGIN_STATUS(state, status: boolean) {
            state.hasLogIn = status
        },
        SET_USER_INFO(state, payload: Partial<UserInfo>) {
            state.userInfo = {
                ...state.userInfo,
                ...payload
            }
            uni.setStorageSync('userInfo', state.userInfo)
        },
        HAS_FILLED_DATA(state, val: boolean) {
            state.isFilledData = val
        },
        HAS_ENROLL(state, val: boolean) {
            state.hasEnroll = val
        },
        SET_PERMISSIONS(state, payload: UserPermissionDAT[]) {
            state.permissions = payload
        }
    },

    actions: {
        login: ({ commit, dispatch }) => {
            return new Promise((resolve, reject) => {
                wxLogin().then(async (res) => {
                    const { OPENID, ROLE_ID, ROLENAME, USERNO, CUSER_ID, TOKEN } = res
                    commit('SET_USER_INFO', {
                        OPENID,
                        // SESSION_KEY: '',
                        ROLE_ID,
                        ROLENAME,
                        USERNO,
                        CUSER_ID,
                        TOKEN
                    })
                    if (res.error === 'user_error') {
                        uni.showToast({
                            title: '你的账号已在其他设备登录',
                            icon: 'none',
                            mask: true
                        })
                        dispatch("logout")
                        reject('user_error')
                    } else {
                        uni.setStorageSync('token', res.TOKEN)
                        try {
                            await dispatch('setPermission')

                        } catch (err) {
                            uni.showToast({
                                title: '登录异常，请重试',
                                icon: 'none',
                                mask: true
                            })
                            dispatch('logout')
                        }
                        commit('SET_LOGIN_STATUS', true)
                        commit('SET_USER_INFO', {
                            USERNAME: res.USERNAME
                        })
                        commit('HAS_FILLED_DATA', res.ZL_FLAG == '1')
                        commit('HAS_ENROLL', res.ENROLL_FLAG == '1')
                        // const dataRes = await getUserData(res.CUSER_ID)
                        // if (dataRes.ERROR[0].errcode == '0'){
                        //     commit('HAS_FILLED_DATA', dataRes.COUNT[0].NUM != 0)
                        // }
                        resolve(res)
                    }
                })
            })
        },

        setPermission: ({ state, commit }) => {
            return getPermission(state.userInfo.CUSER_ID).then(res => {
                if (res.ERROR[0].errcode == '0') {
                    commit('SET_PERMISSIONS', res.DAT)
                }
            })
        },

        logout: ({ commit, state }): void => {
            const OPENID = state.userInfo.OPENID
            uni.removeStorageSync('token')
            uni.removeStorageSync('userInfo')
            commit('SET_LOGIN_STATUS', false)
            commit('SET_PERMISSIONS', [])
            commit('HAS_FILLED_DATA', false)
            commit('HAS_ENROLL', false)
            commit('SET_USER_INFO', {
                OPENID,
                ROLE_ID: '',
                ROLENAME: '',
                USERNO: '',
                CUSER_ID: '',
                TOKEN: '',
            })
            uni.reLaunch({
                url: '/pages/index/index'
            })
        }
    }
}

export default userStore
